<template>
  <section 
    id="testimonials" 
    class="section-padding transition-all duration-300"
    :style="getBackgroundStyles()"
  >
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 标题区域 -->
      <div class="text-center max-w-3xl mx-auto mb-16">
        <span 
          class="font-medium inline-block mb-2"
          :style="{ color: primaryColor }"
        >
          {{ subtitle }}
        </span>
        <h2 
          class="section-title text-3xl md:text-4xl font-bold mb-4"
          :style="{ color: titleColor }"
        >
          {{ title }}
        </h2>
        <p 
          class="section-subtitle text-dark/70"
          :style="{ color: descriptionColor }"
        >
          {{ description }}
        </p>
      </div>
      
      <!-- 客户评价列表 -->
      <div 
        :class="getGridClasses()"
        class="gap-8"
      >
        <!-- 加载状态 -->
        <div v-if="isLoading" class="col-span-full flex justify-center items-center py-16">
          <div class="flex flex-col items-center">
            <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primaryColor"></div>
            <p class="mt-4 text-dark/70">正在加载评价数据...</p>
          </div>
        </div>
        
        <!-- 评价项 -->
        <div 
          v-else-if="testimonialsWithState.length > 0"
          v-for="(testimonial, index) in testimonialsWithState" 
          :key="index"
          class="p-8 rounded-xl transition-all duration-300"
          :style="{
            backgroundColor: cardBgColor,
            borderRadius: `${cardRadius}px`,
            boxShadow: cardShadow
          }"
          @mouseenter="handleCardHover(index, true)"
          @mouseleave="handleCardHover(index, false)"
        >
          <div class="flex items-center mb-6">
            <img 
              :src="testimonial.avatar" 
              :alt="testimonial.name" 
              class="w-14 h-14 rounded-full object-cover mr-4"
              :style="{ filter: testimonial.isHovered ? 'grayscale(0)' : 'grayscale(50%)', transition: 'filter 0.3s ease' }"
            >
            <div>
              <h4 
                class="font-bold"
                :style="{ color: nameColor }"
              >
                {{ testimonial.name }} - {{ testimonial.company }}
              </h4>
              <div class="flex mt-1">
                <i 
                  class="fa fa-star" 
                  v-for="(star, i) in 5" 
                  :key="i"
                  :style="{ 
                    color: i < testimonial.rating ? ratingColor : '#d1d5db',
                    transition: 'color 0.3s ease'
                  }"
                ></i>
              </div>
            </div>
          </div>
          <p 
            class="text-dark/80 italic mb-4"
            :style="{ color: commentColor }"
          >
            "{{ testimonial.comment }}"
          </p>
          <p 
            class="text-dark/60 text-sm"
            :style="{ color: projectColor }"
          >
            合作项目：{{ testimonial.project }}
          </p>
        </div>
        
        <!-- 无数据状态 -->
        <div v-else class="col-span-full flex justify-center items-center py-16">
          <div class="text-center">
            <i class="fa fa-comments-o text-5xl text-dark/30 mb-4"></i>
            <p class="text-dark/70">暂无评价数据</p>
          </div>
        </div>
      </div>
      
      <!-- 满意度数据 -->
      <div 
        v-if="showStats"
        class="mt-20 rounded-2xl p-8 lg:p-12"
        :style="{
          backgroundColor: statsBgColor,
          borderRadius: `${statsRadius}px`
        }"
      >
        <div class="flex flex-col lg:flex-row items-center">
          <div class="w-full lg:w-1/2 mb-10 lg:mb-0 lg:pr-10">
            <h3 
              class="text-2xl font-bold mb-4"
              :style="{ color: statsTitleColor }"
            >
              {{ statsTitle }}
            </h3>
            <p 
              class="text-dark/70 mb-6"
              :style="{ color: statsDescriptionColor }"
            >
              {{ statsDescription }}
            </p>
            <div class="space-y-4">
              <div v-for="(stat, i) in stats" :key="i">
                <div class="flex justify-between mb-1">
                  <span 
                    class="font-medium"
                    :style="{ color: statLabelColor }"
                  >
                    {{ stat.label }}
                  </span>
                  <span 
                    class="font-bold"
                    :style="{ color: primaryColor }"
                  >
                    {{ stat.value }}
                  </span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2 overflow-hidden">
                  <div 
                    class="h-2 rounded-full transition-all duration-1500 ease-out"
                    :style="{ 
                      backgroundColor: primaryColor,
                      width: stat.percentage ? `${stat.percentage}%` : '0%'
                    }"
                    :data-value="stat.percentage"
                    ref="statBars"
                  ></div>
                </div>
              </div>
            </div>
          </div>
          <div class="w-full lg:w-1/2">
            <div 
              class="p-4 rounded-xl shadow-md"
              :style="{
                backgroundColor: chartCardBgColor,
                borderRadius: `${chartCardRadius}px`,
                boxShadow: chartCardShadow
              }"
            >
              <canvas 
                :id="`resultsChart-${id}`" 
                width="400" 
                height="300"
                ref="chartCanvas"
              ></canvas>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
import { defineComponent, ref, onMounted, nextTick, watch } from 'vue';

// 引入Chart.js
import Chart from 'chart.js/auto'
export default defineComponent({
  name: 'TestimonialsSection',
  // 低代码平台元数据
  lowcode: {
    meta: {
      name: 'testimonials-section',
      displayName: '客户评价模块',
      description: '展示客户评价、满意度数据和成果图表的模块',
      icon: 'fa-comments',
      category: '内容展示',
      version: '1.0.0',
      isContainer: false
    },
    
    configPanel: [
      {
        title: '基本配置',
        fields: [
          {
            name: 'primaryColor',
            label: '主题色',
            type: 'color',
            defaultValue: '#165DFF'
          },
          {
            name: 'title',
            label: '主标题',
            type: 'text',
            defaultValue: '客户对我们的评价'
          },
          {
            name: 'subtitle',
            label: '副标题',
            type: 'text',
            defaultValue: '客户评价'
          },
          {
            name: 'description',
            label: '描述文本',
            type: 'textarea',
            defaultValue: '来自各行各业客户的真实反馈，见证我们的服务质量和专业能力'
          },
          {
            name: 'showStats',
            label: '显示统计数据',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'dataSourceUrl',
            label: '数据源URL',
            type: 'text',
            defaultValue: '',
            description: 'API接口地址，用于动态加载评价数据'
          },
          {
            name: 'autoLoad',
            label: '自动加载数据',
            type: 'boolean',
            defaultValue: true
          }
        ]
      },
      {
        title: '布局配置',
        fields: [
          {
            name: 'columns',
            label: '列数',
            type: 'select',
            options: [
              { label: '1列', value: 1 },
              { label: '2列', value: 2 },
              { label: '3列', value: 3 },
              { label: '4列', value: 4 }
            ],
            defaultValue: 3
          },
          {
            name: 'gap',
            label: '间距(px)',
            type: 'number',
            min: 0,
            max: 100,
            defaultValue: 32
          }
        ]
      },
      {
        title: '样式配置',
        fields: [
          {
            name: 'backgroundType',
            label: '背景类型',
            type: 'select',
            options: [
              { label: '纯色', value: 'solid' },
              { label: '渐变色', value: 'gradient' }
            ],
            defaultValue: 'solid'
          },
          {
            name: 'bgColor',
            label: '背景色',
            type: 'color',
            defaultValue: '#ffffff'
          },
          {
            name: 'bgColor2',
            label: '渐变背景色2',
            type: 'color',
            defaultValue: '#f9fafb'
          },
          {
            name: 'titleColor',
            label: '主标题颜色',
            type: 'color',
            defaultValue: '#1f2937'
          },
          {
            name: 'descriptionColor',
            label: '描述文本颜色',
            type: 'color',
            defaultValue: 'rgba(31, 41, 55, 0.7)'
          },
          {
            name: 'cardBgColor',
            label: '评价卡片背景色',
            type: 'color',
            defaultValue: '#f9fafb'
          },
          {
            name: 'cardRadius',
            label: '卡片圆角(px)',
            type: 'number',
            min: 0,
            max: 30,
            defaultValue: 12
          },
          {
            name: 'cardShadow',
            label: '卡片阴影',
            type: 'text',
            defaultValue: '0 4px 6px -1px rgba(0, 0, 0, 0.05)'
          },
          {
            name: 'cardHoverEffect',
            label: '卡片悬停效果',
            type: 'select',
            options: [
              { label: '提升效果', value: 'lift' },
              { label: '阴影加深', value: 'shadow' },
              { label: '颜色变化', value: 'color' },
              { label: '无效果', value: 'none' }
            ],
            defaultValue: 'lift'
          }
        ]
      },
      {
        title: '评价内容配置',
        fields: [
          {
            name: 'testimonials',
            label: '评价列表',
            type: 'array',
            defaultValue: [
              {
                name: '刘总',
                company: '某金融机构',
                avatar: 'https://picsum.photos/seed/client11/100/100',
                rating: 5,
                comment: '智联科技的团队专业且高效，他们为我们提供的数字化转型解决方案超出了预期，帮助我们在激烈的市场竞争中保持领先地位。',
                project: '全渠道数字化服务平台建设'
              },
              {
                name: '张经理',
                company: '某制造企业',
                avatar: 'https://picsum.photos/seed/client12/100/100',
                rating: 4.5,
                comment: '通过智联科技的智能制造解决方案，我们的生产效率提升了35%，成本降低了20%。他们不仅提供技术支持，还帮助我们优化了业务流程。',
                project: '智能生产管理系统实施'
              },
              {
                name: '王总',
                company: '某零售集团',
                avatar: 'https://picsum.photos/seed/client13/100/100',
                rating: 5,
                comment: '智联科技帮助我们实现了线上线下一体化经营，客户体验得到显著提升，销售额也有了大幅增长。他们的服务非常专业，响应迅速。',
                project: '全渠道零售平台建设'
              }
            ]
          },
          {
            name: 'nameColor',
            label: '客户名称颜色',
            type: 'color',
            defaultValue: '#1f2937'
          },
          {
            name: 'ratingColor',
            label: '评分星星颜色',
            type: 'color',
            defaultValue: '#f59e0b'
          },
          {
            name: 'commentColor',
            label: '评价内容颜色',
            type: 'color',
            defaultValue: 'rgba(31, 41, 55, 0.8)'
          },
          {
            name: 'projectColor',
            label: '项目名称颜色',
            type: 'color',
            defaultValue: 'rgba(31, 41, 55, 0.6)'
          }
        ]
      },
      {
        title: '统计数据配置',
        fields: [
          {
            name: 'statsTitle',
            label: '统计标题',
            type: 'text',
            defaultValue: '客户满意度与成果'
          },
          {
            name: 'statsDescription',
            label: '统计描述',
            type: 'textarea',
            defaultValue: '我们始终以客户满意度为核心，不断提升服务质量和专业能力。通过我们的解决方案，客户实现了显著的业务增长和效率提升。'
          },
          {
            name: 'stats',
            label: '统计数据项',
            type: 'array',
            defaultValue: [
              { label: '客户满意度', value: '98.7%', percentage: 98.7 },
              { label: '项目按时交付率', value: '96.5%', percentage: 96.5 },
              { label: '客户业务增长率', value: '平均32.8%', percentage: 85 }
            ]
          },
          {
            name: 'statsBgColor',
            label: '统计区域背景色',
            type: 'color',
            defaultValue: 'rgba(22, 93, 255, 0.05)'
          },
          {
            name: 'statsRadius',
            label: '统计区域圆角(px)',
            type: 'number',
            min: 0,
            max: 30,
            defaultValue: 16
          },
          {
            name: 'statsTitleColor',
            label: '统计标题颜色',
            type: 'color',
            defaultValue: '#1f2937'
          },
          {
            name: 'statsDescriptionColor',
            label: '统计描述颜色',
            type: 'color',
            defaultValue: 'rgba(31, 41, 55, 0.7)'
          },
          {
            name: 'statLabelColor',
            label: '统计项标签颜色',
            type: 'color',
            defaultValue: '#1f2937'
          }
        ]
      },
      {
        title: '图表配置',
        fields: [
          {
            name: 'showChart',
            label: '显示图表',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'chartType',
            label: '图表类型',
            type: 'select',
            options: [
              { label: '柱状图', value: 'bar' },
              { label: '折线图', value: 'line' },
              { label: '雷达图', value: 'radar' }
            ],
            defaultValue: 'bar'
          },
          {
            name: 'chartData',
            label: '图表数据',
            type: 'object',
            properties: [
              { name: 'labels', type: 'array', defaultValue: ['效率提升', '成本降低', '客户满意度', '业务增长', '项目成功率'] },
              { name: 'values', type: 'array', defaultValue: [35, 28, 98, 42, 96] },
              { name: 'colors', type: 'array', defaultValue: ['rgba(22, 93, 255, 0.8)', 'rgba(22, 93, 255, 0.6)', 'rgba(22, 93, 255, 0.4)', 'rgba(22, 93, 255, 0.3)', 'rgba(22, 93, 255, 0.7)'] }
            ]
          },
          {
            name: 'chartCardBgColor',
            label: '图表卡片背景色',
            type: 'color',
            defaultValue: '#ffffff'
          },
          {
            name: 'chartCardRadius',
            label: '图表卡片圆角(px)',
            type: 'number',
            min: 0,
            max: 30,
            defaultValue: 12
          },
          {
            name: 'chartCardShadow',
            label: '图表卡片阴影',
            type: 'text',
            defaultValue: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
          }
        ]
      }
    ],
    
    events: [
      {
        name: 'testimonialClick',
        label: '评价卡片点击',
        description: '当点击客户评价卡片时触发',
        parameters: [
          { name: 'testimonial', type: 'object', description: '评价信息对象' },
          { name: 'index', type: 'number', description: '评价索引' }
        ]
      },
      {
        name: 'cardHover',
        label: '卡片悬停',
        description: '当鼠标悬停在评价卡片上时触发',
        parameters: [
          { name: 'index', type: 'number', description: '评价索引' },
          { name: 'isHovered', type: 'boolean', description: '是否悬停状态' }
        ]
      },
      {
        name: 'dataLoaded',
        label: '数据加载完成',
        description: '从数据源加载数据完成时触发',
        parameters: [
          { name: 'data', type: 'array', description: '加载的评价数据' }
        ]
      },
      {
        name: 'dataLoadError',
        label: '数据加载失败',
        description: '从数据源加载数据失败时触发',
        parameters: [
          { name: 'error', type: 'object', description: '错误信息' }
        ]
      }
    ],
    
    actions: [
      {
        name: 'updateTestimonials',
        label: '更新评价列表',
        description: '更新客户评价数据',
        parameters: [
          { name: 'testimonials', type: 'array', required: true, description: '新的评价列表' }
        ]
      },
      {
        name: 'updateStats',
        label: '更新统计数据',
        description: '更新满意度统计数据',
        parameters: [
          { name: 'stats', type: 'array', required: true, description: '新的统计数据' }
        ]
      },
      {
        name: 'refreshChart',
        label: '刷新图表',
        description: '重新渲染统计图表'
      },
      {
        name: 'refresh',
        label: '刷新评价数据',
        description: '重新从数据源加载评价数据'
      }
    ]
  },
  
  props: {
    // 基本配置
    primaryColor: {
      type: String,
      default: '#165DFF'
    },
    
    // 数据源配置
    dataSourceUrl: {
      type: String,
      default: ''
    },
    
    autoLoad: {
      type: Boolean,
      default: true
    },
    title: {
      type: String,
      default: '客户对我们的评价'
    },
    subtitle: {
      type: String,
      default: '客户评价'
    },
    description: {
      type: String,
      default: '来自各行各业客户的真实反馈，见证我们的服务质量和专业能力'
    },
    showStats: {
      type: Boolean,
      default: true
    },
    
    children: {
      type: Array,
      default: () => []
    },
    // 布局配置
    columns: {
      type: Number,
      default: 3,
      validator: (value) => [1, 2, 3, 4].includes(value)
    },
    gap: {
      type: Number,
      default: 32,
      validator: (value) => value >= 0 && value <= 100
    },
    
    // 样式配置
    backgroundType: {
      type: String,
      default: 'solid',
      validator: (value) => ['solid', 'gradient'].includes(value)
    },
    bgColor: {
      type: String,
      default: '#ffffff'
    },
    bgColor2: {
      type: String,
      default: '#f9fafb'
    },
    titleColor: {
      type: String,
      default: '#1f2937'
    },
    descriptionColor: {
      type: String,
      default: 'rgba(31, 41, 55, 0.7)'
    },
    cardBgColor: {
      type: String,
      default: '#f9fafb'
    },
    cardRadius: {
      type: Number,
      default: 12,
      validator: (value) => value >= 0 && value <= 30
    },
    cardShadow: {
      type: String,
      default: '0 4px 6px -1px rgba(0, 0, 0, 0.05)'
    },
    cardHoverEffect: {
      type: String,
      default: 'lift',
      validator: (value) => ['lift', 'shadow', 'color', 'none'].includes(value)
    },
    
    // 评价内容配置
    testimonials: {
      type: Array,
      default: () => [
        {
          name: '刘总',
          company: '某金融机构',
          avatar: 'https://picsum.photos/seed/client11/100/100',
          rating: 5,
          comment: '智联科技的团队专业且高效，他们为我们提供的数字化转型解决方案超出了预期，帮助我们在激烈的市场竞争中保持领先地位。',
          project: '全渠道数字化服务平台建设'
        },
        {
          name: '张经理',
          company: '某制造企业',
          avatar: 'https://picsum.photos/seed/client12/100/100',
          rating: 4.5,
          comment: '通过智联科技的智能制造解决方案，我们的生产效率提升了35%，成本降低了20%。他们不仅提供技术支持，还帮助我们优化了业务流程。',
          project: '智能生产管理系统实施'
        },
        {
          name: '王总',
          company: '某零售集团',
          avatar: 'https://picsum.photos/seed/client13/100/100',
          rating: 5,
          comment: '智联科技帮助我们实现了线上线下一体化经营，客户体验得到显著提升，销售额也有了大幅增长。他们的服务非常专业，响应迅速。',
          project: '全渠道零售平台建设'
        }
      ]
    },
    nameColor: {
      type: String,
      default: '#1f2937'
    },
    ratingColor: {
      type: String,
      default: '#f59e0b'
    },
    commentColor: {
      type: String,
      default: 'rgba(31, 41, 55, 0.8)'
    },
    projectColor: {
      type: String,
      default: 'rgba(31, 41, 55, 0.6)'
    },
    
    // 统计数据配置
    statsTitle: {
      type: String,
      default: '客户满意度与成果'
    },
    statsDescription: {
      type: String,
      default: '我们始终以客户满意度为核心，不断提升服务质量和专业能力。通过我们的解决方案，客户实现了显著的业务增长和效率提升。'
    },
    stats: {
      type: Array,
      default: () => [
        { label: '客户满意度', value: '98.7%', percentage: 98.7 },
        { label: '项目按时交付率', value: '96.5%', percentage: 96.5 },
        { label: '客户业务增长率', value: '平均32.8%', percentage: 85 }
      ]
    },
    statsBgColor: {
      type: String,
      default: 'rgba(22, 93, 255, 0.05)'
    },
    statsRadius: {
      type: Number,
      default: 16,
      validator: (value) => value >= 0 && value <= 30
    },
    statsTitleColor: {
      type: String,
      default: '#1f2937'
    },
    statsDescriptionColor: {
      type: String,
      default: 'rgba(31, 41, 55, 0.7)'
    },
    statLabelColor: {
      type: String,
      default: '#1f2937'
    },
    
    // 图表配置
    showChart: {
      type: Boolean,
      default: true
    },
    chartType: {
      type: String,
      default: 'bar',
      validator: (value) => ['bar', 'line', 'radar'].includes(value)
    },
    chartData: {
      type: Object,
      default: () => ({
        labels: ['效率提升', '成本降低', '客户满意度', '业务增长', '项目成功率'],
        values: [35, 28, 98, 42, 96],
        colors: ['rgba(22, 93, 255, 0.8)', 'rgba(22, 93, 255, 0.6)', 'rgba(22, 93, 255, 0.4)', 'rgba(22, 93, 255, 0.3)', 'rgba(22, 93, 255, 0.7)']
      })
    },
    chartCardBgColor: {
      type: String,
      default: '#ffffff'
    },
    chartCardRadius: {
      type: Number,
      default: 12,
      validator: (value) => value >= 0 && value <= 30
    },
    chartCardShadow: {
      type: String,
      default: '0 4px 6px -1px rgba(0, 0, 0, 0.1)'
    }
  },
  
  setup(props, { emit }) {
    // 响应式数据
    const id = Math.random().toString(36).substring(2, 10);
    const testimonialsWithState = ref([]);
    const statBars = ref([]);
    const chartCanvas = ref(null);
    let chartInstance = null;
    const isLoading = ref(false);
    const originalTestimonials = ref([]);
    const localTestimonials = ref([]);
    
    // 初始化评价数据，添加状态属性
    const initializeTestimonials = () => {
      originalTestimonials.value = [...props.testimonials];
      localTestimonials.value = [...props.testimonials];
      testimonialsWithState.value = props.testimonials.map(item => ({
        ...item,
        isHovered: false
      }));
    };
    
    // 处理卡片悬停
    const handleCardHover = (index, isHovered) => {
      if (index >= 0 && index < testimonialsWithState.value.length) {
        testimonialsWithState.value[index].isHovered = isHovered;
        emit('cardHover', { index, isHovered });
      }
    };
    
    // 处理评价卡片点击
    const handleTestimonialClick = (testimonial, index) => {
      emit('testimonialClick', { testimonial, index });
    };
    
    // 从API数据源加载数据
    const loadDataFromSource = async () => {
      if (!props.dataSourceUrl) {
        console.warn('数据源URL为空，无法加载数据');
        return;
      }
      
      isLoading.value = true;
      
      try {
        // 发送请求获取数据
        const response = await fetch(props.dataSourceUrl);
        
        if (!response.ok) {
          throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
        
        const data = await response.json();
        
        // 验证数据格式
        let validData;
        if (Array.isArray(data)) {
          validData = data;
        } else if (data.testimonials && Array.isArray(data.testimonials)) {
          validData = data.testimonials;
        } else {
          throw new Error('数据格式不正确，需要包含评价数组');
        }
        
        // 更新本地数据
        originalTestimonials.value = [...validData];
        localTestimonials.value = [...validData];
        testimonialsWithState.value = validData.map(item => ({
          ...item,
          isHovered: false
        }));
        
        // 通知父组件
        emit('update:testimonials', [...validData]);
        emit('dataLoaded', validData);
      } catch (error) {
        console.error('从数据源加载数据失败:', error);
        emit('dataLoadError', error);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 刷新评价数据
    const refresh = () => {
      if (props.dataSourceUrl) {
        loadDataFromSource();
      } else {
        // 重置为原始数据
        localTestimonials.value = [...originalTestimonials.value];
        testimonialsWithState.value = originalTestimonials.value.map(item => ({
          ...item,
          isHovered: false
        }));
        emit('update:testimonials', [...originalTestimonials.value]);
      }
    };
    
    // 获取背景样式
    const getBackgroundStyles = () => {
      const styles = {};
      
      if (props.backgroundType === 'solid') {
        styles.backgroundColor = props.bgColor;
      } else {
        styles.background = `linear-gradient(to bottom right, ${props.bgColor}, ${props.bgColor2})`;
      }
      
      return styles;
    };
    
    // 获取网格布局类
    const getGridClasses = () => {
      const baseClasses = 'grid';
      const columnClasses = `grid-cols-1 ${props.columns >= 2 ? 'md:grid-cols-2' : ''} ${props.columns >= 3 ? 'lg:grid-cols-3' : ''} ${props.columns >= 4 ? 'xl:grid-cols-4' : ''}`;
      const gapClass = `gap-${Math.floor(props.gap / 4)}`; // 转换为Tailwind的gap单位
      
      return `${baseClasses} ${columnClasses} ${gapClass}`;
    };
    
    // 初始化统计条动画
    const initializeStatBars = () => {
      nextTick(() => {
        if (statBars.value.length) {
          statBars.value.forEach(bar => {
            if (bar) {
              const value = bar.dataset.value;
              bar.style.width = '0%';
              // 触发重排后设置宽度以启动动画
              setTimeout(() => {
                bar.style.width = `${value}%`;
              }, 100);
            }
          });
        }
      });
    };
    
    // 初始化图表
    const initializeChart = () => {
      if (!props.showChart || !chartCanvas.value) return;
      
      // 销毁已存在的图表
      if (chartInstance) {
        chartInstance.destroy();
      }
      
      const ctx = chartCanvas.value.getContext('2d');
        
        // 图表配置
        const config = {
          type: props.chartType,
          data: {
            labels: props.chartData.labels,
            datasets: [{
              label: '成果指标(%)',
              data: props.chartData.values,
              backgroundColor: props.chartData.colors,
              borderColor: props.primaryColor,
              borderWidth: 1,
              ...(props.chartType === 'radar' && {
                pointBackgroundColor: props.primaryColor,
                pointBorderColor: '#fff',
                pointHoverBackgroundColor: '#fff',
                pointHoverBorderColor: props.primaryColor
              })
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: props.chartType !== 'radar' && {
              y: {
                beginAtZero: true,
                max: 100,
                ticks: {
                  callback: function(value) {
                    return value + '%';
                  }
                }
              }
            },
            plugins: {
              legend: {
                display: false
              }
            },
            animation: {
              duration: 2000,
              easing: 'easeOutQuart'
            }
          }
        };
        
        // 创建图表实例
        chartInstance = new Chart(ctx, config);
    };
    
    // 刷新图表
    const refreshChart = () => {
      initializeChart();
    };
    
    // 更新评价列表
    const updateTestimonials = (newTestimonials) => {
      if (Array.isArray(newTestimonials)) {
        testimonialsWithState.value = newTestimonials.map(item => ({
          ...item,
          isHovered: false
        }));
      }
    };
    
    // 更新统计数据
    const updateStats = (newStats) => {
      if (Array.isArray(newStats)) {
        // 在实际使用中，这里应该通过props或状态管理更新stats
        // 这里仅做演示，实际项目中可能需要配合v-model或状态管理
        initializeStatBars();
      }
    };
    
    // 监听数据变化
    watch(() => props.testimonials, () => {
      initializeTestimonials();
    }, { deep: true });
    
    watch(() => props.stats, () => {
      initializeStatBars();
    }, { deep: true });
    
    // 监听数据源URL变化
    watch(() => props.dataSourceUrl, () => {
      if (props.autoLoad) {
        loadDataFromSource();
      }
    });
    
    // 组件挂载时初始化
    onMounted(() => {
      initializeTestimonials();
      initializeStatBars();
      initializeChart();
      
      if (props.autoLoad && props.dataSourceUrl) {
        loadDataFromSource();
      }
    });
    
    return {
      id,
      testimonialsWithState,
      statBars,
      chartCanvas,
      isLoading,
      originalTestimonials,
      localTestimonials,
      handleCardHover,
      handleTestimonialClick,
      getBackgroundStyles,
      getGridClasses,
      updateTestimonials,
      updateStats,
      refreshChart,
      loadDataFromSource,
      refresh
    };
  }
});
</script>

<style scoped>
/* 卡片悬停效果 */
.hover-lift:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.hover-shadow:hover {
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.hover-color:hover {
  background-color: var(--hover-bg-color);
}

/* 评价卡片动画 */
.rounded-xl {
  transition: all 0.3s ease;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .mt-20 {
    margin-top: 4rem !important;
  }
}

@media (max-width: 768px) {
  .section-padding {
    padding-top: 2rem !important;
    padding-bottom: 2rem !important;
  }
  
  .mb-16 {
    margin-bottom: 3rem !important;
  }
  
  h2.text-3xl {
    font-size: 1.8rem !important;
  }
  
  .mt-20 {
    margin-top: 3rem !important;
  }
}
</style>
    